package com.kaiyiweitong.tongxing.util;

import android.app.Activity;
import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.kaiyiweitong.tongxing.constant.HttpConstant;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/12/22 0022.
 */

public class HttpUtil {
    private static final String TAG = "HttpUtil";
    private static final String STATE = "state";
    private static final OkHttpClient mOkHttpClient = new OkHttpClient();
    private static String result;//请求结果

    static {
        mOkHttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
    }

    /**
     * 自定义回调
     */
    public interface MyCallBack {
        void onResult(String result);
    }

    /**
     * @param inter    网络请求接口名
     * @param params   参数
     * @param activity
     * @param callback
     */
    public static void get(String inter, Map<String, String> params, final Activity activity, final MyCallBack callback) {
        List<BasicNameValuePair> pairs = new ArrayList<>();

        pairs.add(new BasicNameValuePair("m", "api"));
        String[] arr = inter.split("/");
        pairs.add(new BasicNameValuePair("c", arr[0]));
        pairs.add(new BasicNameValuePair("a", arr[1]));

        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        String url = HttpConstant.MAIN_PATH + "?" + URLEncodedUtils.format(pairs, "UTF-8");

        mOkHttpClient.newCall(new Request.Builder().url(url).build()).enqueue(new Callback() {
            @Override
            public void onResponse(final Response response) {
                if (response.isSuccessful()) {
                    try {
                        result = response.body().string();
                    } catch (Exception e) {
                        LogUtils.errorLog(TAG, e.toString());
                        e.printStackTrace();
                    } finally {
                        activity.runOnUiThread(new Runnable() {//切换到主线程
                            @Override
                            public void run() {
                                callback.onResult(result);
                            }
                        });
                    }
                } else {
                    LogUtils.errorLog(TAG, "response is fail");
                    callback.onResult("");
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {

            }
        });
    }

    public static String getState(String result) {
        if (result == null || result.equals("")) {
            return "";
        } else {
            return JSON.parseObject(result).getString(STATE);
        }
    }

    public static boolean isSuccessState(String result) {
        if (result == null || result.equals("")) {
            LogUtils.errorLog(TAG, "result is null or \"\" ");
            return false;
        } else {
            if ("1".equals(JSON.parseObject(result).getString(STATE))) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 解析非数组对象
     *
     * @param context
     * @param result
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T checkResponse(Context context, String result, Class<T> clazz) {
        if (result != null && !"".equals(result.trim())) {
            try {
                return JSON.parseObject(result, clazz);
            } catch (Exception e) {
                LogUtils.errorLog(TAG, e.toString());
                return null;
            }
        } else {
            LogUtils.errorLog(TAG, "result is null or \"\" ");
            return null;
        }
    }

    /**
     * 解析数组对象
     *
     * @param context
     * @param result
     * @param clazz
     * @return
     */
    public static <T> List<T> checkArrayResponse(Context context, String result, Class<T> clazz) {
        if (result != null && !"".equals(result.trim())) {
            try {
                return JSON.parseArray(result, clazz);
            } catch (Exception e) {
                LogUtils.errorLog(TAG, e.toString());
                return null;
            }
        } else {
            LogUtils.errorLog(TAG, "result is null or \"\" ");
            return null;
        }
    }
}